import router from './router'
import store from './store'
import NProgress from 'nprogress'
import conf from './config'
import { getStore, removeStore } from '@/utils/store'

const storeKey = conf.key.route

NProgress.configure({ showSpinner: false })

if (!store.getters.addRoutes.length && getStore(storeKey)) {
  try {
    store.dispatch('permission/generateRoutes', JSON.parse(getStore(storeKey)))
  } catch (e) {
    removeStore(storeKey)
  }
}

let isLoaded = false
router.beforeEach((to, _, next) => {
  NProgress.start()
  if (store.getters.addRoutes.length) {
    if (!isLoaded) {
      store.getters.addRoutes.length && router.addRoutes(store.getters.addRoutes)
      isLoaded = true
      next({ ...to, replace: true })
    } else {
      next()
      NProgress.done()
    }
  } else {
    if (to.path !== '/Dashboard') {
      next('/Dashboard')
    } else {
      next()
      NProgress.done()
    }
  }
})

router.afterEach(route => {
  const title = route.meta.title
  document.title = title ? (title + ' | ' + process.env.VUE_APP_TITLE) : process.env.VUE_APP_TITLE
  NProgress.done()
})
